const axios = require('axios');
const readline = require('readline');
const { RemoteAgent } = require('./remoteAgent');

async function LoadDataset() {
    try {
        let url = 'http://localhost:3000/LoadDataset';
        let data = {
            dataset_id: 'lrkor2kh0ogu',
            load_details: true,
            page: 1,
            page_size: 100
        };
        const response = await axios.post(url, data);
        return response.data;
    } catch (error) {
        console.error('Error LoadDataset:', error.message);
        return {};
    }
}

async function LoadImage(image_path) {
    try {
        let url = `http://localhost:3000/LoadImage?image_path=${encodeURIComponent(image_path)}`;
        const startTime = new Date();
        await axios.get(url);
        const endTime = new Date();
        const requestTime = endTime - startTime;
        console.log(`Request [${url}] time:`, requestTime, 'milliseconds');
    } catch (error) {
        console.error('Error LoadImage:', error.message);
    }
}

async function testPerformance() {
    let result = await LoadDataset();
    if (result.code == 0) {
        const startTime0 = new Date();

        for (let i = 0; i < result.msg.data.length; i++) {
            let data = result.msg.data[i];
            let image_path = data.image_path;

            const startTime = new Date();
            await LoadImage(image_path);
            const endTime = new Date();
            const requestTime = endTime - startTime;
            console.log(`Request [${image_path}] time:`, requestTime, 'milliseconds');

            // LoadImage(image_path);
        }

        const endTime0 = new Date();
        const requestTime0 = endTime0 - startTime0;
        console.log(`Request Total Time:`, requestTime0, 'milliseconds');
    }
}

// 调用RemoteAgent的示例
async function testRemoteAgent() {
    const sshConfig = {
        host: '106.13.144.101',
        port: 22,
        username: 'work',
        password: 'martin0905',
        tunnel_src_port: null,
        tunnel_dst_port: null
    };
    const remote = new RemoteAgent(null, sshConfig);
    try {
        await remote.connect();
        // await remote.uploadFile('local-file.txt', 'remote-file.txt');
        let result = null;
        result = await remote.createTunnel({
            src_port: 3001,
            dst_port: 3000
        });
        // result = await remote.executeCommand('ls -l');
        // result = await remote.executeCommand('ls -la');
        // await remote.downloadFile('remote-file.txt', 'local-file-downloaded.txt');
        console.log('Press Enter to disconnect...');

        // 创建 readline 接口
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        // 监听用户输入
        rl.on('line', async () => {
            await remote.disconnect();
            rl.close();
        });

        // 等待用户按回车键
        await new Promise((resolve) => rl.on('close', resolve));
    } catch (error) {
        console.error('Error:', error);
    }
}

async function addRemote(remoteInfo) {
    // let { name, host, port, username, password, identity_file } = remoteInfo;
    try {
        let url = 'http://localhost:3000/AddRemote';
        const response = await axios.post(url, remoteInfo);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error addRemote:', error.message);
        return {};
    }
}

async function getRemoteList() {
    try {
        let url = `http://localhost:3000/GetRemoteList`;
        let result = await axios.get(url);
        console.log(result.data.msg);
    } catch (error) {
        console.error('Error getRemoteList:', error.message);
    }
}

async function getRemoteInfo(remoteId) {
    try {
        let url = `http://localhost:3000/GetRemoteInfo`;
        let data = {
            remoteId: remoteId
        };
        const response = await axios.post(url, data);
        console.log(response.data.msg);
        return response.data;
    } catch (error) {
        console.error('Error getRemoteInfo:', error.message);
    }
}

async function connectRemote(remoteId) {
    try {
        let url = 'http://localhost:3000/RemoteConnect';
        let data = {
            remoteId: remoteId
        };
        const response = await axios.post(url, data);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error connectRemote:', error.message);
        return {};
    }
}

async function disconnectRemote(remoteId) {
    try {
        let url = 'http://localhost:3000/RemoteDisconnect';
        let data = {
            remoteId: remoteId
        };
        const response = await axios.post(url, data);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error disconnectRemote:', error.message);
        return {};
    }
}

async function executeCommand(remoteId, command) {
    try {
        let url = 'http://localhost:3000/RemoteExecutor';
        let data = {
            remoteId: remoteId,
            command: command
        };
        const response = await axios.post(url, data);
        console.log(response.data.msg);
        return response.data;
    } catch (error) {
        console.error('Error LoadDataset:', error.message);
        return {};
    }
}

async function ping(remoteId) {
    let result = await getRemoteInfo(remoteId);
    // console.log(result);
    if (result.code < 0) {
        console.error(`No remote found with ${remoteId}`);
        return {};
    }

    try {
        let url = `http://localhost:${result.msg.tunnel_src_port}/Ping`;
        const response = await axios.get(url);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error ping:', error.message);
        return {};
    }
}

async function test(remoteId) {
    try {
        let url = `http://localhost:3000/RemoteTest?remoteId=${remoteId}`;
        const response = await axios.get(url);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error test remote connection:', error.message);
        return {};
    }
}

// 创建readline界面
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const promptMessage = `
Enter command:
- add: Add a new remote
- list: Get list of all the remote
- info <id>: Get information of a remote with specified ID
- connect <id>: Connect remote using ssh tunnel with specified ID
- disconnect <id>: Disconnect remote with specified ID
- execute <id> <cmd>: Execute command on remote machine using ssh tunnel with specified ID
- ping: Play Ping-Pong
- test: Test remote if connected
- help: Print help information
- exit: Exit the program
`;
console.log(promptMessage);

const promptForAction = () => {
    rl.question('>> ', async (command) => {
        const args = command.split(' ');
        const action = args[0];
        switch (action.trim()) {
            case 'add':
                await addRemote();
                break;
            case 'list':
                await getRemoteList();
                break;
            case 'info':
                await getRemoteInfo(args[1]);
                break;
            case 'connect':
                await connectRemote(args[1]);
                break;
            case 'disconnect':
                await disconnectRemote(args[1]);
                break;
            case 'execute':
                await executeCommand(args[1], args[2]);
                break;
            case 'ping':
                await ping(args[1]);
                break;
            case 'test':
                await test(args[1]);
                break;
            case 'help':
                console.log(promptMessage);
                break;
            case 'exit':
                rl.close();
                break;
            case '':
                break;
            default:
                console.log(`Unknown command "${action}"`);
                break;
        }
        promptForAction();
    });
};

// 处理readline界面关闭
rl.on('close', () => {
    console.log('Exiting the program.');
    process.exit(0);
});

// 开始循环
promptForAction();
